package com.hwz.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.hwz.common.constant.ProductConstant;
import com.hwz.common.to.SkuHasStockTo;
import com.hwz.common.to.SkuReductionTo;
import com.hwz.common.to.SpuBoundsTo;
import com.hwz.common.to.es.SkuEsModel;
import com.hwz.common.utils.R;
import com.hwz.gulimall.product.dao.SpuInfoDescDao;
import com.hwz.gulimall.product.entity.*;
import com.hwz.gulimall.product.feign.CouPonFeignService;
import com.hwz.gulimall.product.feign.SearchFeignService;
import com.hwz.gulimall.product.feign.WareFeignService;
import com.hwz.gulimall.product.service.*;
import com.hwz.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwz.common.utils.PageUtils;
import com.hwz.common.utils.Query;

import com.hwz.gulimall.product.dao.SpuInfoDao;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescDao spuInfoDescDao;

    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    CouPonFeignService couPonFeignService;


    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;


    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    BrandService brandService;


    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2、保存spu的描述图片
        List<String> decriptList = vo.getDecript();
        String decript = String.join(",", decriptList);
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(decript);
        spuInfoDescDao.insert(spuInfoDescEntity);
        //3、保存spu的图片集
        spuImagesService.saveBatch(spuInfoEntity.getId(), vo.getImages());
        //4、保存spu的规格参数
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            AttrEntity attr = attrService.getById(baseAttr.getAttrId());
            productAttrValueEntity.setAttrName(attr.getAttrName());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);

        //5、保存spu的积分信息
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        Bounds bounds = vo.getBounds();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couPonFeignService.saveCouPon(spuBoundsTo);
        if (r.getCode() != 0){
            throw new RuntimeException("远程服务调用失败");
        }


        //6、保存sku信息
        for (Skus sku :vo.getSkus()) {
            //6.1、保存sku基本信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            if (sku.getImages() != null && !sku.getImages().isEmpty()){
                List<Images> collect = sku.getImages().stream().filter(image -> image.getDefaultImg() == 1).collect(Collectors.toList());
                if (collect.size() > 0){
                    skuInfoEntity.setSkuDefaultImg(collect.get(0).getImgUrl()); //设置默认图片
                }
            }
            BeanUtils.copyProperties(sku,skuInfoEntity);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoService.save(skuInfoEntity);
            //6.2、保存sku的图片信息
            if (sku.getImages() != null && !sku.getImages().isEmpty()){
                List<SkuImagesEntity> skuImagesEntityList = sku.getImages().stream().filter(image -> !StringUtils.isEmpty(image.getImgUrl())).map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);
            }

            //6.3、保存sku的销售属性
            List<SkuSaleAttrValueEntity> saleAttrValueEntityList = sku.getAttr().stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);

                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());

            skuSaleAttrValueService.saveBatch(saleAttrValueEntityList);

            //6.4、保存sku的优惠满减信息

            //封装好to后远程调用服务进行保存

            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(sku,skuReductionTo);
            skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
            R r1 = couPonFeignService.saveSkuReduction(skuReductionTo);
            if (r1.getCode() != 0){
                throw new RuntimeException("远程服务调用失败");
            }

        }



    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(params.get("key"))){
            spuInfoEntityQueryWrapper.and(obj -> obj.eq("id", params.get("key")).or().like("spu_name", params.get("key")));
        }

        if (!StringUtils.isEmpty(params.get("status"))){
            spuInfoEntityQueryWrapper.eq("publish_status", params.get("status"));
        }

        if (!StringUtils.isEmpty(params.get("brandId")) && !"0".equals(params.get("brandId"))){
            spuInfoEntityQueryWrapper.eq("brand_id", params.get("brandId"));
        }

        if (!StringUtils.isEmpty(params.get("catelogId")) && !"0".equals(params.get("catelogId"))){
            spuInfoEntityQueryWrapper.eq("catalog_id", params.get("catelogId"));
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }
    //上架商品
    @Override
    public void up(Long spuId) {
        //1、查询当前spuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        //封装为esSkuModel保存到es中去
        SkuInfoEntity skuInfo1 = skus.get(0);
        BrandEntity brandInfo = brandService.getById(skuInfo1.getBrandId());
        CategoryEntity categoryInfo = categoryService.getById(skuInfo1.getCatalogId());

        //查询spu的基础规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //查询属性的基本信息
        List<Long> searchIds = attrService.selectSearchAttrs(attrIds);
        HashSet<Long> attrIdSet = new HashSet<>(searchIds);

        List<SkuEsModel.Attr> attrs = baseAttrs.stream().filter(item -> attrIdSet.contains(item.getAttrId())).map(item -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;
        try {
            List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            List<SkuHasStockTo> hasStockTos = wareFeignService.hasStock(skuIds);
           stockMap = hasStockTos.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        } catch (Exception e) {
            log.error("远程服务调用失败");
        }

        List<SkuEsModel> skuEsModels = new ArrayList<>();
        for (SkuInfoEntity skuInfo : skus) {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfo,skuEsModel);
            //1、调用库存服务查询是否有库存

            if (stockMap == null|| stockMap.isEmpty()){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(stockMap.get(skuInfo.getSkuId()) == null ? true : stockMap.get(skuInfo.getSkuId()));
            }
            //2、设置商品得分
            skuEsModel.setHotScore(0l);
            //3、设置品牌信息
            skuEsModel.setBrandName(brandInfo.getName());
            skuEsModel.setBrandImg(brandInfo.getLogo());
            skuEsModel.setBrandId(skuInfo.getBrandId());
            //4、设置分类信息
            skuEsModel.setCatalogId(skuInfo.getCatalogId());
            skuEsModel.setCatalogName(categoryInfo.getName());
            //5、设置sku的属性信息
            skuEsModel.setAttrs(attrs);
            //6、设置sku价格
            skuEsModel.setSkuPrice(skuInfo.getPrice());
            //7、设置sku图片
            skuEsModel.setSkuImg(skuInfo.getSkuDefaultImg());

            skuEsModels.add(skuEsModel);
        }


        //保存数据到es
        R r = searchFeignService.productStatusUp(skuEsModels);
        if (r.getCode() == 0){ //保存成功
            //更新spu状态为上架
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {  //保存失败

        }


        System.out.println(skuEsModels);




    }

}